package com.leetcode;

/**
 * <p>
 * 【银泰面试题】 2021.3.3 面试题
 * 两个线程交替打印1-100的整数，一个打印奇数，一个打印偶数，要求输出结果有序。
 * synchronized + Object#wait / notifyAll
 * ReentrantLock + Condition#await / signalAll ---> 这种也需要实现
 * </p>
 * @author: Sunny
 * @date: 2021/3/3
 * @version: v1.0.0
 */
public class OddEvenNumber {

    private final Object monitor = new Object();

    private int limit;

    private int count;

    public OddEvenNumber(int limit, int count) {
        this.limit = limit;
        this.count = count;
    }

    public void print() {
        synchronized (monitor) {
            while (count < limit) {
                try {
                    System.out.println(Thread.currentThread().getName() + "打印 : " + ++count);
                    monitor.notifyAll();
                    monitor.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        OddEvenNumber oddEvenNumberDemo = new OddEvenNumber(100, 0);
        // 打印奇数
        Thread t1 = new Thread(() -> {
            oddEvenNumberDemo.print();
        },"t1");
        // 打印偶数
        Thread t2 = new Thread(() -> {
            oddEvenNumberDemo.print();
        },"t2");
        t1.start();
        t2.start();
    }
}

